package com.dao;

import com.domain.Chatter;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class ChatterDAOImpl implements ChatterDAO {

    @Resource
    private SessionFactory sessionFactory;

    @Transactional
    public void addUser(Chatter chatter) {
        sessionFactory.getCurrentSession().save(chatter);
    }

    @Transactional
    public List<Chatter> getUsers() {
        return sessionFactory.getCurrentSession().createQuery("from Chatter ").list();
    }

    @Transactional
    public void removeUser(String nickname) {

        Chatter chatter = (Chatter) sessionFactory.getCurrentSession().get(Chatter.class, nickname);
        if (!chatter.getName().isEmpty()) {
            sessionFactory.getCurrentSession().delete(chatter);
        }
    }

    @Transactional
    public Long countUsers(String nickname) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Chatter.class);
        criteria.add(Restrictions.eq("name", nickname));
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.list().get(0);

    }
}
